import { useTheme } from 'antd-style';
import "./aichat.css"
import { memo, useEffect, useLayoutEffect, useRef, useState } from 'react';
import { Image } from 'antd';
import { Drawer } from 'antd';
import WebSocketNode from '../../components/WebSocketNode.tsx';
import useAudioRecorder from "../../hooks/useAudioRecorder.ts";
import ChatWhite from './ChatWhite.tsx';
import globalData from '../../store/global.ts';


interface Props {
    open: boolean;
    onClose: () => void;
}

const AiChat = (props: Props) => {
    const { open, onClose } = props;

    const theme = useTheme();
    const [title, setTitle] = useState("AI助手")
    const [visible, setVisible] = useState(false);
    const [imgUrl, setImgUrl] = useState("");
    const [startRun, setStartRun] = useState(false);

    // 播放音频
    const playAudio = async (audioUrl: any) => {
        const url = import.meta.env.VITE_LLM_API_API + "/" + audioUrl
        try {
            const response = await fetch(url, {
                method: "GET"
            });

            if (!response.ok) {
                throw new Error("HTTP error " + response.status);
            }

            const blob = await response.blob();
            const blobURL = window.URL.createObjectURL(blob);
            const audio = new Audio(blobURL);

            // 添加加载事件监听
            audio.onloadeddata = () => {
                console.log("音频已加载");
            };

            // 添加错误事件监听
            audio.onerror = (e) => {
                console.error("音频加载失败:", e);
                window.URL.revokeObjectURL(blobURL);
            };

            audio.onended = () => {
                window.URL.revokeObjectURL(blobURL);
            };

            // 处理自动播放策略
            try {
                await audio.play();
                console.log("开始播放");
            } catch (error) {
                console.error("播放失败，可能需要用户交互:", error);
            }
        } catch (error) {
            console.error("音频处理失败:", error);
        }
    }

    useLayoutEffect(() => {
        const userId = parseInt(Math.random() * 1000000 + "").toString();
        globalData.userId = userId;
    }, [])

    useEffect(() => {
        if (open) {
            setTitle("运行")
        }
    }, [open])

    return (
        <Drawer
            footer={null}
            title={<div>{title}</div>}
            open={open}
            width={450}
            onClose={() => onClose()}
            destroyOnClose={true}
            maskClosable={false}
            mask={startRun}
            maskClassName='custom-mask'
            style={{ background: 'white' }}
        >
            <div style={{ background: theme.colorBgLayout, height: "calc(100% - 24px)" }}
                className='overflow-hidden'
                onClick={(e) => {
                    // 获取e的元素
                    const target = e.target as HTMLElement;
                    // 如果当前元素是img标签 获取url
                    if (target.tagName === 'IMG') {
                        const url = target.getAttribute('src');
                        setImgUrl(url);
                        setVisible(true);
                    }
                }}
            >
                <ChatWhite sidebar={false} onRun={setStartRun} />
            </div>
            {/* <div className='flex justify-center mt-2'>
                <Button onClick={toggleRecording} icon={isRecording ? <AudioOutlined /> : <AudioMutedOutlined />} >
                    {isRecording ? '停止说话' : '开始说话'}
                </Button>
            </div> */}

            {/** 展示图片 */}
            <Image
                width={200}
                style={{ display: 'none' }}
                src={imgUrl}
                preview={{
                    visible,
                    src: imgUrl,
                    onVisibleChange: (value) => {
                        setVisible(value);
                    },
                }}
            />
            <WebSocketNode />
        </Drawer>
    );
};

export default memo(AiChat)